//
//  HomeViewController.swift
//  maosheng
//
//  Created by 何海涛 on 2019/7/30.
//

import Foundation
import UIKit
import JXSegmentedView
class HomeViewController: RootViewController {
    let segmentedView = JXSegmentedView()
    let segmentedDataSource = JXSegmentedTitleDataSource()
    let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 40))
    var titleArr = [String]()
    var navArr = NSMutableArray()
    var topTitleArr : [HomeNavModel]?

    let homeView = HomeTableView()
    override func viewDidLoad() {
        super.viewDidLoad()
        getKeywords()
        setTopSegmentView()
    }
    func setTopSegmentView() -> Void {
//        searchBar.delegate = self
        
//       searchBar.backgroundColor = KYP_f2f2f2_COLOR
//        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 35))
//        titleView.addSubview(searchBar)
        UISearchBar.appearance().tintColor = .black
        searchBar.placeholder = "搜索"
        self.navigationItem.titleView = searchBar
        let seachTextFeild = searchBar.subviews.first?.subviews.last
        seachTextFeild?.backgroundColor = KYP_f2f2f2_COLOR
        seachTextFeild!.layer.cornerRadius = 17.5
        seachTextFeild!.layer.masksToBounds = true
        searchBar.delegate = self
        if #available(iOS 11.0, *) {
            searchBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
        }
        
        view.addSubview(homeView)
        homeView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.top.equalTo(45)
        }
        homeView.didUpdateTopList = {[weak self] (need) in
            if self?.topTitleArr == nil{
                self?.getKeywords()
            }
        }
        homeView.didClickRow = {[weak self](row,blogId) in
            self?.jumpDetailVC(blogId: blogId!)
        }
//        self.setTopView(typeArr: [HomeNavModel()])

        
    
    }
    func jumpDetailVC(blogId : String) {
        let detail = HomeDetailController()
        detail.str_title = "详情"
        detail.blogId = blogId
        detail.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(detail, animated: true)
    }
    func getKeywords() {
        let url =  "api/services/app/Category/GetCategoriesAsync"
        var params = [String : Any]()
        params["ModuleTypeId"] = 100301
        params["IsOnlyRoot"] = true

        SDataCenter.shared.SGetJsonDataWithUrl(str_url: url, params: params) { (responseData, isSuccess) in
            if isSuccess && responseData is Array<Any>{
                if let arr = responseData as? Array<Any>{
                    if let typeArr = [HomeNavModel].deserialize(from: arr){
                        self.topTitleArr = typeArr as? [HomeNavModel]
                        DispatchQueue.main.async {
                            self.setTopView(typeArr: typeArr as! [HomeNavModel])
                        }
                    }
                }
             
                
            }else{
                
                
            }
        }
    }
    func setTopView(typeArr:[HomeNavModel]) -> Void {
        navArr.addObjects(from: ["关注", "推荐", "热点","本地"])
        for model in typeArr {
            var displayName = model.displayName
            if displayName == nil{
                displayName = ""
            }
            navArr.add(displayName!)
        }
        
  
        
        //关联dataSource
        self.segmentedView.dataSource = self.segmentedDataSource
        let indicator = JXSegmentedIndicatorLineView()
        indicator.lineStyle = .lengthen
        self.segmentedView.indicators = [indicator]
        self.segmentedView.defaultSelectedIndex = 1
        segmentedView.backgroundColor = .white
        segmentedView.delegate = self
        view.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(0)
            make.height.equalTo(45)
        }
        self.segmentedDataSource.titles = navArr as! [String]
        //配置数据源相关配置属性
        self.segmentedDataSource.isTitleColorGradientEnabled = true
        //         self.segmentedDataSource
        //        reloadData(selectedIndex:)方法一定要调用，方法内部会刷新数据源数组
        self.segmentedDataSource.reloadData(selectedIndex: 1)
    }
    
    
    
}
extension HomeViewController : JXSegmentedViewDelegate,UISearchBarDelegate{
    //点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，而不关心具体是点击还是滚动选中的情况。
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        homeView.params.removeValue(forKey: "CategoryIds")
        if index > 3{
            if let categoryId = topTitleArr?[index - 4].blogId{
                homeView.params["CategoryIds"] = categoryId
            }
        }
        homeView.currentIndex = index
        homeView.str_url = index == 0 ? "api/services/app/Blog/GetMyIndustryBlogPagingListAsync" : "api/services/app/Blog/GetBlogPagingListAsync"
        homeView.getTheHomeNewsList(isHeader: true)
        
        
        
        print(index)
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        homeView.searchText = searchBar.text
        homeView.getTheHomeNewsList(isHeader: true)
        searchBar.perform(#selector(resignFirstResponder), with: nil, afterDelay: 0.1)
    }
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        homeView.searchText = nil
        homeView.getTheHomeNewsList(isHeader: true)

    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.count == 0{
            homeView.searchText = nil
            searchBar.perform(#selector(resignFirstResponder), with: nil, afterDelay: 0.1)
            homeView.getTheHomeNewsList(isHeader: true)

        }
    }
//
//    // 点击选中的情况才会调用该方法
//    func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) {}
//    
//    // 滚动选中的情况才会调用该方法
//    func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) {}
//
//    // 正在滚动中的回调
//    func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) {}

}
